package com.chunfeng.lerunapplication.grid;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import com.chunfeng.lerunapplication.R;

/**
 * 九宫格布局适配器
 *
 * @author by 春风能解释
 * <p>
 * 2023/12/11
 */
public class GridAdapt extends BaseAdapter {
    /**
     * 图片集合
     */
    private int[] images = {
            R.drawable.zodiac_mouse,
            R.drawable.zodiac_cattle,
            R.drawable.zodiac_tiger,
            R.drawable.zodiac_rabbit,
            R.drawable.zodiac_dragon,
            R.drawable.zodiac_snake,
            R.drawable.zodiac_horse,
            R.drawable.zodiac_sheep,
            R.drawable.zodiac_monkey,
            R.drawable.zodiac_chicken,
            R.drawable.zodiac_dog,
            R.drawable.zodiac_pig
    };

    /**
     * 总数量
     *
     * @return 数量
     */
    @Override
    public int getCount() {
        return images.length;
    }

    /**
     * 获取每一项
     *
     * @param position 索引
     * @return 每一项
     */
    @Override
    public Object getItem(int position) {
        return position;
    }

    /**
     * 获取每一项对应的布局ID
     *
     * @param position 索引
     * @return 该项的布局ID
     */
    @Override
    public long getItemId(int position) {
        return images[position];
    }

    /**
     * 获取视图布局
     *
     * @param position    索引
     * @param convertView 容器布局
     * @param parent      父容器
     * @return 当前布局对象
     */
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        GridHolder holder;
        if (convertView == null) {
            convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_grid_item, parent, false);
            holder = new GridHolder(convertView.findViewById(R.id.GridImage));
            convertView.setTag(holder);
        } else {
            holder = (GridHolder) convertView.getTag();
        }
        holder.imageView.setBackgroundResource(images[position]);
        return convertView;
    }
}
